﻿using HomeCloudStorageSystem.Dtos;
using HomeCloudStorageSystem.Models;
using HomeCloudStorageSystem.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

namespace HomeCloudStorageSystem.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class FileDirectorysController : ControllerBase
    {
        private readonly IFileDirectoryRepository _fileDirectoryRepository;
        private readonly IUserRepository _userRepository;
        public FileDirectorysController(IFileDirectoryRepository fileDirectoryRepository, IUserRepository userRepository)
        {
            _fileDirectoryRepository = fileDirectoryRepository;
            _userRepository = userRepository;
        }
        /// <summary>
        /// 根据父级目录 ID 查看目录信息，父级目录 ID为空时，返回所有父级目录 ID为空的目录的信息
        /// </summary>
        /// <param name="parentId">父级目录 ID为空</param>
        /// <returns>目录信息类别</returns>
        [HttpGet]
        public IActionResult GetDirectorys([FromQuery] int? parentId)
        {
            if (parentId <= 0 || string.IsNullOrEmpty(parentId.ToString()))
            {
                parentId = 0;
            }
            var fileDirectoryFromRep = _fileDirectoryRepository.GetFileDirectorys(parentId);
            return Ok(fileDirectoryFromRep);
        }
        /// <summary>
        /// 添加目录
        /// </summary>
        /// <param name="fileDirectoryForCreationDto"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult CreateFileDirectory([FromBody] FileDirectoryForCreationDto fileDirectoryForCreationDto)
        {
            var userName = User.Claims.FirstOrDefault(n => n.Type == ClaimTypes.NameIdentifier)?.Value;
            var userInfo = _userRepository.GetUserByUserName(userName);
            fileDirectoryForCreationDto.Creator = userInfo.Id;

            if (fileDirectoryForCreationDto == null)
            {
                return BadRequest("目录信息不能为空");
            }
            var message = _fileDirectoryRepository.AddFileDirectory(fileDirectoryForCreationDto);
            return Ok(message);
        }
        /// <summary>
        /// 根据 ID 删除目录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public IActionResult DeleteFileDirectory([FromRoute] int id)
        {
            if (id <= 0 || string.IsNullOrEmpty(id.ToString()))
            {
                return BadRequest("错误的请求");
            }
            var fileDirectoryFromRep = _fileDirectoryRepository.GetFileDirectoryById(id);
            if (fileDirectoryFromRep == null)
            {
                return NotFound("没有该资源");
            }
            var message = _fileDirectoryRepository.RemoveFileDirectory(fileDirectoryFromRep);
            return Ok(message);
        }
    }
}
